<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { useGetRegisterCodeList } from '@/services/pages/code'
  import { TableInstance } from 'element-plus'
  import { nextTick, PropType, ref, watch } from 'vue'
  import { RefreshRight } from '@element-plus/icons-vue'

  const {
    registeredCodeList,
    registeredCodeListTotal,
    getRegisterCodeListLoading,
    getRegisteredCodeListParam,
    resetParam,
    getRegisterCodeList,
  } = useGetRegisterCodeList()

  defineOptions({
    name: 'GoodSelectModalReturnFactoryCreate',
  })

  const props = defineProps({
    userId: {
      type: String,
      default: () => '',
    },
    defaultSelectGood: {
      type: Array as PropType<Array<{ goodId: string; goodSpecId: string; snCode: string }>>,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'select-good', value: Array<CodeRegisteredCodeList>): void
    (e: 'del-good', value: Array<CodeRegisteredCodeList>): void
    (e: 'del-all-good'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 设备选择列表
  const selectGoodList = ref<Array<CodeRegisteredCodeList>>([])

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 需要删除的设备列表
  const delGoodList = ref<Array<CodeRegisteredCodeList>>([])

  /**
   * 获取列表
   */
  const getList = () => {
    if (!props.userId) {
      return
    }

    nextTick(async () => {
      if (paginationInstance.value && tableInstance.value) {
        getRegisteredCodeListParam.value.page = paginationInstance.value.current
        getRegisteredCodeListParam.value.limit = paginationInstance.value.size
        await getRegisterCodeList(props.userId)
        props.defaultSelectGood.forEach((defaultSelectGood) => {
          registeredCodeList.value.forEach((registeredCode) => {
            if (
              defaultSelectGood.goodId === registeredCode.goodsId &&
              defaultSelectGood.goodSpecId === registeredCode.goodsSpecId &&
              defaultSelectGood.snCode === registeredCode.code
            ) {
              tableInstance.value.toggleRowSelection(registeredCode, true)
            }
          })
        })
      }
    })
  }

  /**
   * 移除选择的设备
   * @param {Array<CodeRegisteredCodeList>} goodList - 设备列表
   * @param {CodeRegisteredCodeList} row - 设备
   */
  const handleRemoveSelectGood = (
    goodList: Array<CodeRegisteredCodeList>,
    row: CodeRegisteredCodeList,
  ) => {
    selectGoodList.value = goodList
    const isExit = goodList.some(
      (good) =>
        good.goodsId === row.goodsId &&
        good.goodsSpecId === row.goodsSpecId &&
        good.code === row.code,
    )
    if (!isExit) {
      delGoodList.value.push(row)
    }
  }

  /**
   * 选择设备
   * @param {Array<CodeRegisteredCodeList>} goodList - 设备列表
   */
  const handleSelectGood = (goodList: Array<CodeRegisteredCodeList>) => {
    selectGoodList.value = goodList
  }

  /**
   * 选择全选/全部反选
   * @param {Array<CodeRegisteredCodeList>} goodList - 设备列表
   */
  const handleSelectAllGood = (goodList: Array<CodeRegisteredCodeList>) => {
    selectGoodList.value = goodList
    delGoodList.value.length = 0
  }

  /**
   * 关闭弹窗
   */
  const closeDrawer = () => {
    visible.value = false
  }

  /**
   * 确定事件
   */
  const onConfirm = () => {
    closeDrawer()
    emits('select-good', selectGoodList.value)
    emits('del-good', delGoodList.value)
    if (selectGoodList.value.length === 0) {
      emits('del-all-good')
    }
  }

  /**
   * 重置事件
   */
  const onReset = () => {
    resetParam()
    getList()
  }

  watch(
    visible,
    (value) => {
      if (value) {
        getList()
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    :width="1000"
    unit="px"
    title="选择设备"
    :loading="getRegisterCodeListLoading"
    @close="closeDrawer"
  >
    <div class="add-commodity-for-new-return-factory">
      <div class="header">
        <!-- 输入序列号查询 -->
        <el-input
          v-model.trim="getRegisteredCodeListParam.code"
          placeholder="输入序列号查询"
          clearable
          @clear="getList"
          @keyup.enter="getList"
        />

        <!-- 输入设备编号查询 -->
        <el-input
          v-model.trim="getRegisteredCodeListParam.goodsCode"
          placeholder="输入设备编号查询"
          clearable
          @clear="getList"
          @keyup.enter="getList"
        />

        <h-button type="primary" @click="getList">
          <el-icon>
            <Search></Search>
          </el-icon>
          搜索
        </h-button>

        <h-button @click="onReset">
          <el-icon>
            <RefreshRight></RefreshRight>
          </el-icon>
          取消
        </h-button>
      </div>
      <div class="table">
        <el-table
          ref="tableInstance"
          :border="true"
          stripe
          :data="registeredCodeList"
          height="100%"
          @select="handleRemoveSelectGood"
          @select-all="handleSelectAllGood"
          @selection-change="handleSelectGood"
        >
          <el-table-column type="selection" width="50" fixed />

          <!-- 序号 -->
          <el-table-column type="index" width="50" fixed label="序号" :align="'center'" />

          <!-- 序列号 -->
          <el-table-column show-overflow-tooltip prop="code" width="180" label="序列号" />

          <!-- 设备编号 -->
          <el-table-column show-overflow-tooltip prop="goodsCode" width="100" label="设备编号" />

          <!-- 品牌 -->
          <el-table-column show-overflow-tooltip prop="goodsBrand" width="100" label="品牌" />

          <!-- 名称 -->
          <el-table-column show-overflow-tooltip prop="goodsName" width="180" label="名称" />

          <!-- 型号 -->
          <el-table-column show-overflow-tooltip prop="goodsModel" width="120" label="型号" />

          <!-- 规格 -->
          <el-table-column show-overflow-tooltip prop="goodsSpecName" width="160" label="规格" />

          <!-- 合同号 -->
          <el-table-column show-overflow-tooltip prop="contractNo" width="160" label="合同号" />

          <!-- 类型 -->
          <el-table-column show-overflow-tooltip prop="goodsType" width="100" label="类型" />

          <!-- 地址 -->
          <el-table-column show-overflow-tooltip label="地址" width="220">
            <template #default="{ row }">
              {{ `${row.province}   ${row.city}  ${row.area}  ${row.town}  ${row.address}` }}
            </template>
          </el-table-column>

          <!-- 质保时间(天) -->
          <el-table-column prop="warrantyDay" label="质保时间(天)" width="140" />

          <!-- 质保开始 -->
          <el-table-column prop="warrantyStartTime" label="质保开始" width="140" />

          <!-- 质保截止 -->
          <el-table-column prop="warrantyEndTime" label="质保截止" width="140" />
        </el-table>
      </div>
      <div class="pagination">
        <Pagination
          ref="paginationInstance"
          :list_total="registeredCodeListTotal"
          @size-change="getList"
          @page-change="getList"
        />
      </div>
    </div>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="closeDrawer">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .add-commodity-for-new-return-factory {
    height: 99%;
    display: flex;
    flex-direction: column;
    row-gap: 5px;

    .header {
      display: flex;
      column-gap: 5px;
      justify-content: flex-end;

      :deep(.el-input) {
        width: 180px;
      }
    }

    .table {
      max-height: calc(100% - 66px);
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
